﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfApp1.Controller;
using WpfApp1.Entity;
using System.Text.Json;
using System.Diagnostics.Eventing.Reader;
using System.Security.Policy;

namespace WpfApp1
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        private int currentPage = 0;
        private int pageSizes = 10;
        private int totalPages = 0;
        List<CertificateItem> certificateItems;
        private Service.CertificateService.CertificateService _certificateService = new Service.CertificateService.CertificateService();

        public Window1()
        {
            InitializeComponent();
            PageSizeComboBox.SelectedIndex = 0; //默认10
                                                
            DocumentListView.MouseDoubleClick += DocumentListView_MouseDoubleClick;
            LoadData();
        }

        private async void LoadData()
        {
            try
            {
                // 定义请求的 URL
                string apiUrl = FileController.ApiUrl + "/api/certificate/page";

                // 定义请求体
                var requestBody = new
                {
                    page = currentPage,
                    pageSize = pageSizes
                };

                // 将请求体序列化为 JSON 字符串
                string jsonRequestBody = JsonSerializer.Serialize(requestBody);

                // 创建 HttpClient 实例
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
                    client.DefaultRequestHeaders.Add("Authorization", FileController.Token);
                    // 设置请求的 Content-Type 为 application/json
                    var content = new StringContent(jsonRequestBody, Encoding.UTF8, "application/json");

                    // 发送 POST 请求
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                    // 检查响应状态码
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string responseContent = await response.Content.ReadAsStringAsync();

                        var options = new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        };

                        // 反序列化响应内容
                        PageResponse pageResponse = JsonSerializer.Deserialize<PageResponse>(responseContent, options);

                        // 更新总页数
                        totalPages = pageResponse.Result.TotalPages;

                        // 获取 items 数组
                        certificateItems = pageResponse.Result.Items;

                        // 将 items 绑定到 ListView
                        DocumentListView.ItemsSource = certificateItems;

                        UpdateButtonStates();
                    }
                    else
                    {
                        MessageBox.Show($"请求失败，状态码: {response.StatusCode}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误: {ex.Message}");
            }
        }

        private void UpdateButtonStates()
        {
            // 上一页按钮状态
            PreviousPageButton.IsEnabled = currentPage > 0;
            //// 下一页按钮状态
            NextPageButton.IsEnabled = currentPage < totalPages - 1;
        }

        private void PageSizeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PageSizeComboBox.SelectedItem is ComboBoxItem selectedItem)
            {
                pageSizes = int.Parse(selectedItem.Content.ToString());
                currentPage = 0; // 重置为第一页
                LoadData();
            }
        }

        private void PreviousPageButton_Click(object sender, RoutedEventArgs e)
        {
            if (currentPage > 0)
            {
                currentPage--;
                LoadData();
            }
        }

        private void NextPageButton_Click(object sender, RoutedEventArgs e)
        {
            if (currentPage < totalPages - 1)
            {
                currentPage++;
                LoadData();
            }
        }

        private void DocumentListView_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (DocumentListView.SelectedItem != null)
            {
                CertificateItem selectedItem = (CertificateItem)DocumentListView.SelectedItem;
                MainWindow mainWindow = Application.Current.MainWindow as MainWindow;
                if (mainWindow != null)
                {
                    mainWindow.SetDataToControls(selectedItem);
                }
                this.Close();
            }
        }

        private void DeleteMenuItem_Click(object sender, RoutedEventArgs e)
        {
            if (DocumentListView.SelectedItem != null)
            {
                // 获取选中的项
                CertificateItem selectedItem = (CertificateItem)DocumentListView.SelectedItem;

                // 确认删除操作
                MessageBoxResult result = MessageBox.Show("确定要删除此项吗？", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    _certificateService.deleteForm(selectedItem.Id);

                    // 从数据源中移除选中的项
                    certificateItems.Remove(selectedItem);

                    // 刷新 ListView
                    DocumentListView.Items.Refresh();
                }
            }
        }
    }
}
